function [varargout] = spm_unvec(vX,varargin)
% unvectorises a vectorised array
% FORMAT [X] = spm_unvec(vX,X);
% X  - numeric, cell or structure array
% vX - spm_vec(X)
%
% i.e. X      = spm_unvec(spm_vec(X),X)
%      [X{:}] = spm_unvec(spm_vec(X{:}),X{:})
%                                              - (i.e. can also deal)
%
% see spm_vec
%__________________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Eduardo Aponte

% deal to multiple outputs if necessary
%--------------------------------------------------------------------------

if nargout > 1
    varargout = spm_unvec(vX,varargin);
    return
end
if length(varargin) == 1
    X  = varargin{1};
else
    X  = varargin;
end

% vectorise first argument
%--------------------------------------------------------------------------
if ~isvector(vX)
    vX = spm_vec(vX);
end
n0 = 0;
[n1,oX] = spm_unvec_r(vX,X,n0);
varargout = {oX};
end

function [n0,oX] = spm_unvec_r(vX,X,n0)

% reshape numerical arrays
%--------------------------------------------------------------------------
if isnumeric(X) || islogical(X)
    n1 = numel(X) + n0;
    if ndims(X) > 2
        X(:)  = full(vX(n0+1:n1));
    else
        X(:)  = vX(n0+1:n1);
    end
    oX = X;
    n0 = n1;
    return
end

% fill in structure arrays
%--------------------------------------------------------------------------
if isstruct(X)
    f = fieldnames(X);
    for i = 1:length(f)
        c          = {X.(f{i})};
        [n0,c]     = spm_unvec_r(vX,c,n0);
        [X.(f{i})] = deal(c{:});
    end
    oX      = X;
    return
end

% fill in cell arrays
%--------------------------------------------------------------------------
if iscell(X)
    for i = 1:numel(X)
        [n0,X{i}]  = spm_unvec_r(vX,X{i},n0);
    end
    oX = X;
    return
end

% else
%--------------------------------------------------------------------------
oX         = [];

end